package com.csnf.dao;

import com.csnf.entity.Authors;
import com.csnf.entity.Books;
import com.csnf.util.JdbcUtil;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;

public class AuthorDao {
    public List<Authors> getAuthorsList() throws Exception {
        Connection conn = JdbcUtil.getConnection();
        String sql = "select * from authors";
        PreparedStatement ps = JdbcUtil.getPreparedStatement(conn, sql);
        ResultSet rs = ps.executeQuery();
        List<Authors> authorsList = new ArrayList<>();
        while (rs.next()){
            Authors authors = JdbcUtil.invokeObject(rs, Authors.class);
            authorsList.add(authors);
        }
        JdbcUtil.close(rs,ps,conn);
        return authorsList;
    }

    public Authors getAuthorById(Integer author_id) throws Exception{
        Connection conn = JdbcUtil.getConnection();
        String sql = "select * from authors where author_id=?";
        PreparedStatement ps = JdbcUtil.getPreparedStatement(conn, sql, author_id);
        ResultSet rs = ps.executeQuery();
        Authors authors = new Authors();
        if(rs.next()){
            authors = JdbcUtil.invokeObject(rs, Authors.class);
        }
        BookDao bookDao = new BookDao();
        List<Books> booksByAuthor = bookDao.getBooksByAuthor(authors.getAuthor_id());
        authors.setBooksList(booksByAuthor);
        return authors;
    }
}
